﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using DC.Utils;
using Newtonsoft.Json;

namespace DC.Views
{
    public partial class Form_Settings : Skin_DevExpress
    {
        public Form_Settings()
        {
            InitializeComponent();
        }

        public bool saved = false;
        public bool isfirst = true;
        private void Form_Settings_Load(object sender, EventArgs e)
        {
            if (!isfirst)
            {
                ServerProperty serverProperty = JsonConvert.DeserializeObject<ServerProperty>
                    (FileHelper.ReadFile(Application.StartupPath + "\\config\\database.json"));
                skinTextBox1.Text = serverProperty.Host;
                skinTextBox2.Text = serverProperty.User;
                skinTextBox3.Text = serverProperty.Password;
                skinTextBox4.Text = serverProperty.DatabaseName;
            }
        }

        private void skinButton6_Click(object sender, EventArgs e)
        {
            ServerProperty serverProperty = new ServerProperty(skinTextBox1.Text, skinTextBox2.Text, skinTextBox3.Text, skinTextBox4.Text);
            FileHelper.WriteFile(Application.StartupPath + "\\config\\database.json", JsonConvert.SerializeObject(serverProperty));
            this.saved = true;
            Utils.ServerProperty sp = JsonConvert.DeserializeObject<ServerProperty>
                (FileHelper.ReadFile(Application.StartupPath + "\\config\\database.json"));
            Utils.Global.GlobalDB = new Utils.Database(sp);
            Close();
        }

        Thread[] thread;
        int ip = 1;
        int ipmax = 254;
        static string[] LocalIP = GetLocalIP().Split('.');
        string IPRange = string.Format("{0}.{1}.{2}.", LocalIP[0], LocalIP[1], LocalIP[2]);
        int n; //找到了几个

        private void skinButton1_Click(object sender, EventArgs e)
        {
            skinButton1.Enabled = false;
            int ThreadCount = Convert.ToInt32(64);  //线程数量
            thread = new Thread[ThreadCount];
            for (int i = 0; i < ThreadCount; i++)
            {
                Thread t = new Thread(ScanThread);
                thread[i] = t;
                thread[i].Start();
            }
        }
        public void ScanThread(object obj)
        {
            while (true)
            {
                int nowip;
                lock (this)
                {
                    if (ip > ipmax)
                    {
                        ip = 1;
                        return;
                    }
                    else
                    {
                        nowip = ip;
                        ip++;
                    }
                }
                if (TCPing(IPRange + nowip.ToString(), 1433))
                {
                    n++;
                    SetText(IPRange + nowip.ToString());
                    SetTextStatus(true);
                }
            }
        }
        private void SetText(string text)
        {
            if (skinTextBox1.InvokeRequired)
            {
                Action<string> action = new Action<string>(SetText);
                Invoke(action, new object[] { text });
            }
            else
            {
                skinTextBox1.Text = text;
            }
        }
        private void SetTextStatus(bool value)
        {
            if (skinTextBox1.InvokeRequired)
            {
                Action<bool> action = new Action<bool>(SetTextStatus);
                Invoke(action, new object[] { value });
            }
            else
            {
                skinButton1.Enabled = value;
            }
        }
        private bool TCPing(string IP, int Port)
        {
            try
            {
                TcpClient client = new TcpClient();       //创建一个TcpClient实例
                IPAddress address = IPAddress.Parse(IP);  //转化string类型的ip地址到IpAddress
                IAsyncResult ar = client.BeginConnect(address, Port, null, null);
                bool success = ar.AsyncWaitHandle.WaitOne(300);
                if (success)
                {
                    client.Close();
                    return true;
                }
                else
                {
                    return false;
                }
            }

            catch (Exception)
            {
                return false;
            }
        }
        public static string GetLocalIP()
        {
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }
    }
}
